package com.appspot.bs24event.controller.gyojitter;

import org.apache.log4j.Logger;

import java.util.List;
import org.slim3.controller.BaseController;
import org.slim3.controller.Navigation;
import org.slim3.util.RequestLocator;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;


public class GyojitterController extends BaseController {
    /** ログ */
    protected static final Logger logger = Logger.getLogger(GyojitterController.class.getName());

    @Override
    protected Navigation setUp() {
        logger.info(this.getClass().getName() + " start.");
        return super.setUp();
    }

    @Override
    protected void tearDown() {
        logger.info(this.getClass().getName() + " end.");
        super.tearDown();
    }

    private Twitter twitter;

    @Override
    public Navigation run() throws Exception {
        logger.info(RequestLocator.get());

        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing home timeline!");
        for (Status status : statuses) {
            System.out.println(status.getUser().getName() + ":" + status.getText());
        }
//        requestScope("tweet", statuses);
//        return forward("gyojitter.jsp");
        request.setAttribute("tweet", statuses);
        return forward(request,"gyojitter.jsp");
    }

    public GyojitterController(){
        this.getInstance();
    }

    private void getInstance(){
        TwitterFactory factory = new TwitterFactory();
        twitter = factory.getInstance();
    }

    public void twitterAPITest(){
        try{
            this.getHomeTimeline();
        }catch(TwitterException te){
            te.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void getHomeTimeline() throws TwitterException{
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing home timeline.");
        for (Status status : statuses) {
            System.out.println(status.getUser().getName() + ":" + status.getText());
        }
        requestScope("tweets", statuses);
    }
}